package service

import (
	"anban/models"
	"github.com/astaxie/beego/orm"
	"net/url"
)

type StudentRelationValue struct {
	Id    int64  `json:"id"`
	Value string `json:"value"`
}

// 获取关系信息
func GetStudentRelationInfo(p map[string]interface{}) *models.StudentRelation {
	o := orm.NewOrm()
	studentRelation := &models.StudentRelation{}
	qs := o.QueryTable("StudentRelation")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	qs.One(studentRelation)
	return studentRelation
}

// 添加关系信息
func AddStudentRelation(input url.Values) (int64, error) {
	o := orm.NewOrm()
	studentRelation := &models.StudentRelation{}
	if _, ok := input["name"]; ok {
		studentRelation.Name = input["name"][0]
	}
	return o.Insert(studentRelation)
}

// 修改关系信息
func EditStudentRelation(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("StudentRelation").Filter("id", input["id"][0]).Update(p)
}

// 获取关系列表
func GetStudentRelationList(p map[string]interface{}) (int64, []*models.StudentRelation) {
	var studentRelationList []*models.StudentRelation
	o := orm.NewOrm()
	qs := o.QueryTable("StudentRelation")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.All(&studentRelationList)
	return totalCount, studentRelationList
}

func GetStudentRelationListValues(studentRelationList []*models.StudentRelation) []*StudentRelationValue {
	data := []*StudentRelationValue{}
	for _, studentRelation := range studentRelationList {
		studentRelationVal := &StudentRelationValue{
			Id:    studentRelation.Id,
			Value: studentRelation.Name,
		}
		data = append(data, studentRelationVal)
	}
	return data
}